RM        = rm -frv
CD        = cd
MKDIR     = mkdir -p
CMAKE     = cmake

ifeq ("$(shell which ninja 2> /dev/null)", "")
MAKEPGR   = make
GENERATOR = "Unix Makefiles"
else
MAKEPGR   = ninja
GENERATOR = "Ninja"
endif

BUILDDIR  = build
BINDIR    = bin
LIBDIR    = lib

all: $(BUILDDIR)/CMakeCache.txt
	@[ -d $(BUILDDIR) ] && $(CD) $(BUILDDIR) && $(MAKEPGR)

test: $(BUILDDIR)/CMakeCache.txt
	@[ -d $(BUILDDIR) ] && $(CD) $(BUILDDIR) && $(MAKEPGR) test

clean:
	@[ -d $(BUILDDIR) ] && cd $(BUILDDIR) && $(MAKEPGR) clean

distclean: clean
	@$(RM) $(BUILDDIR) $(BINDIR) $(LIBDIR)

$(BUILDDIR)/CMakeCache.txt: $(BUILDDIR)
	@$(CD) $(BUILDDIR) && $(CMAKE) -G $(GENERATOR) .. || ($(CD) .. && $(RM) $@)
	@$(CD) $(BUILDDIR) && $(CMAKE) -G $(GENERATOR) .. || ($(CD) .. && $(RM) $@)

$(BUILDDIR):
	@$(MKDIR) $@

.PHONY: clean distclean all test
